const dns = require('dns');
const xlsx = require('xlsx');
const fs = require('fs').promises;
const path = require('path');
const { app } = require('electron');
const { v4: uuidv4 } = require('uuid');


const userDataPath = app.getPath('userData');
const dirPath = path.join(userDataPath, 'U2FsdGVkX199', 'xzV09Wbrz8544E=');
const classfilePath = path.join(dirPath, 'classes.xlsx');
const stufilePath = path.join(dirPath, 'students.xlsx');


async function ensureDirectoryExistence(filePath) {
  const dirname = path.dirname(filePath);
  try {
    await fs.access(dirname);
  } catch {
    await ensureDirectoryExistence(dirname);
    await fs.mkdir(dirname);
  }
}

async function createBook(filePath) {
  let workbook;
  if (await fileExists(filePath)) {
    workbook = xlsx.readFile(filePath);
  } else {
    workbook = xlsx.utils.book_new();
  }
}
async function readExcel(filePath, sheetName) {
  if (!await fileExists(filePath)) return [];
  const workbook = xlsx.readFile(filePath);
  const worksheet = workbook.Sheets[sheetName] || workbook.Sheets[workbook.SheetNames[0]];
  return xlsx.utils.sheet_to_json(worksheet);
}

async function writeExcel(filePath, sheetName, data) {
  let workbook;
  if (await fileExists(filePath)) {
    workbook = xlsx.readFile(filePath);
  } else {
    workbook = xlsx.utils.book_new();
  }
  const worksheet = xlsx.utils.json_to_sheet(data);
  workbook.Sheets[sheetName] = worksheet;
  if (!workbook.SheetNames.includes(sheetName)) {
    xlsx.utils.book_append_sheet(workbook, worksheet, sheetName);
  }
  xlsx.writeFile(workbook, filePath);
}

function ensureNumericFields(student) {
  student.points = Number(student.points) || 0;
  student.attempts = Number(student.attempts) || 0;
  student.corrects = Number(student.corrects) || 0;
  return student;
}

async function fileExists(filePath) {
  try {
    await fs.access(filePath);
    return true;
  } catch {
    return false;
  }
}

const ipcHandlers = {
  async checkNetworkStatus() {
    return new Promise((resolve) => {
      dns.lookup('www.baidu.com', (err) => {
        resolve(!err);
      });
    });
  },
  async initFile() {
    try {
      await fs.mkdir(dirPath, { recursive: true });
      await createBook(classfilePath, 'Classes');
      await createBook(stufilePath, 'Students');
      const existingClassData = await readExcel(classfilePath, 'Classes');
      if (existingClassData.length === 0) {
        existingClassData.push({
          id: '1',
          class_name: '默认班级',
          class_no: '001',
          grade: '一年级'
        });
        await writeExcel(classfilePath, 'Classes', existingClassData);
      }
      return {
        success: true
      };
    } catch (error) {
      return {
        success: false,
        error: error.message
      };
    }
  },
  
  async getClassData() {
    try {
      await fs.mkdir(dirPath, { recursive: true });
      const classData = await readExcel(classfilePath, 'Classes');
      if (classData.length == 0) return { success: true, classes: [] };
      const studentData = await readExcel(stufilePath, 'Students');
      const classesWithCounts = classData.map(cls => ({
        ...cls,
        studentCount: studentData.filter(student => student.class_no == cls.class_no).length
      }));
      return { success: true, classes: classesWithCounts };
    } catch (error) {
      console.error('读取班级信息出错:', error);
      return { success: false, error: error.message };
    }
  },

  async saveClassData(event, classData) {
    try {
      await fs.mkdir(dirPath, { recursive: true });
      const existingData = await readExcel(classfilePath, 'Classes') || [];
      const existingClassNos = existingData.map(item => item.class_no);
      let newClassNo;
      let isUnique = false;
  
      while (!isUnique) {
        newClassNo = uuidv4();
        if (!existingClassNos.includes(newClassNo)) {
          isUnique = true;
        }
      }
  
      const newClassData = {
        id: Date.now(),
        class_name: classData.class_name,
        class_no: newClassNo,
        grade: classData.grade,
      };
  
      const duplicate = existingData.find(item => 
        item.class_name === newClassData.class_name && item.grade === newClassData.grade
      );
      if (duplicate) {
        return { success: false, message: '同年级下已有相同班级名称' };
      }
  
      existingData.push(newClassData);
      await writeExcel(classfilePath, 'Classes', existingData);
      return { success: true, classData: newClassData };
    } catch (error) {
      console.error('保存班级信息出错:', error);
      return { success: false, message: error.message };
    }
  },

  async deleteClassData(event, classNo) {
    try {
      if (!await fileExists(classfilePath)) return { success: false, message: '班级文件不存在' };
      let classData = await readExcel(classfilePath, 'Classes');
      classData = classData.filter(cls => cls.class_no != classNo);
      await writeExcel(classfilePath, 'Classes', classData);
      if (await fileExists(stufilePath)) {
        let studentData = await readExcel(stufilePath, 'Students');
        studentData = studentData.filter(student => student.class_no != classNo);
        await writeExcel(stufilePath, 'Students', studentData);
      }
      return { success: true, message: '班级及其对应学生已成功删除' };
    } catch (error) {
      console.error('删除班级时出错:', error);
      return { success: false, error: error.message };
    }
  },

  async updateStuData(event, students) {
    try {
      if (!await fileExists(stufilePath)) return { success: false, message: '文件不存在' };
      let studentData = await readExcel(stufilePath, 'Students');
      studentData = studentData.map(student => {
        const matchedStudent = students.find(stu => stu.stu_no == student.stu_no);
        return matchedStudent ? { ...student, ...matchedStudent, ...ensureNumericFields(matchedStudent) } : student;
      });
      await writeExcel(stufilePath, 'Students', studentData);
      return { success: true, stufilePath };
    } catch (error) {
      console.error('更新学生数据时出错:', error);
      return { success: false, error: error.message };
    }
  },

  async saveStuData(event, students) {
    try {
      await ensureDirectoryExistence(stufilePath);
      let existingData = await readExcel(stufilePath, 'Students');
      const existingStuNos = existingData.filter(student => student.class_no == students[0].class_no).map(student => student.stu_no);
      const duplicateStuNos = students.filter(student => existingStuNos.includes(student.stu_no)).map(student => student.stu_no);
      if (duplicateStuNos.length > 0) {
        return { success: false, message: `学号已存在: ${duplicateStuNos.join(', ')}` };
      }
      const newStudents = students.map(ensureNumericFields);
      existingData = existingData.concat(newStudents);
      await writeExcel(stufilePath, 'Students', existingData);
      return { success: true, stufilePath };
    } catch (error) {
      console.error('保存学生数据时出错:', error);
      return { success: false, error: error.message };
    }
  },

  async getClassStudentCount(event, classNo) {
    try {
      if (!await fileExists(stufilePath)) return { success: false, message: '学生数据文件不存在' };
      const studentData = await readExcel(stufilePath, 'Students');
      const studentCount = studentData.filter(student => student.class_no == classNo).length;
      return { success: true, classNo, studentCount };
    } catch (error) {
      console.error('获取班级人数失败:', error);
      return { success: false, error: error.message };
    }
  },

  async getClassDataByNo(event, classNo) {
    try {
      if (!await fileExists(classfilePath) || !await fileExists(stufilePath)) {
        await createBook(classfilePath);
        await createBook(stufilePath)
      }
      const classData = await readExcel(classfilePath, 'Classes');
      const classItem = classData.find(cls => cls.class_no == classNo);
      if (!classItem) return { success: false, message: '班级不存在' };
      const students = await readExcel(stufilePath, 'Students');
      const filteredStudents = students.filter(student => student.class_no == classNo);
      return { success: true, class: classItem, students: filteredStudents };
    } catch (error) {
      console.error('获取班级数据失败:', error);
      return { success: false, error: error.message };
    }
  },

  async getStuData() {
    try {
      const students = await readExcel(stufilePath, 'Students');
      return { success: true, students };
    } catch (error) {
      console.error('读取数据失败:', error);
      return { success: false, error: error.message };
    }
  },

  async getStuDataByClassNo(event, classNo) {
    try {
      if (!await fileExists(stufilePath)) return { success: true, students: [] };
      const students = await readExcel(stufilePath, 'Students');
      const filteredStudents = students.filter(student => student.class_no == classNo);
      return { success: true, students: filteredStudents };
    } catch (error) {
      console.error('读取数据失败:', error);
      return { success: false, error: error.message };
    }
  },

  async deleteStuData(event, stuNo) {
    try {
      if (!await fileExists(stufilePath)) return { success: false, message: '文件不存在' };
      let studentData = await readExcel(stufilePath, 'Students');
      studentData = studentData.filter(student => student.stu_no !== stuNo);
      await writeExcel(stufilePath, 'Students', studentData);
      return { success: true };
    } catch (error) {
      console.error('删除失败:', error);
      return { success: false, error: error.message };
    }
  },

  async addPoints(event, data) {
    try {
      if (!await fileExists(stufilePath)) return { success: false, message: '学生数据文件不存在' };
      let studentData = await readExcel(stufilePath, 'Students');
      if (Array.isArray(data)) {
        data.forEach(({ stu_no, points, isRight }) => {
          console.log("isRight", isRight)
          const student = studentData.find(s => s.stu_no == stu_no);
          if (student) {
            if (isRight == 1) {
              student.attempts = Number(student.attempts) || 0;
              student.corrects = Number(student.corrects) || 0;
              student.points = Number(student.points) || 0;
              student.attempts += 1;
              student.corrects += 1;
              student.points += Number(points) || 0;
            } else {
              student.attempts = Number(student.attempts) || 0;
              student.corrects = Number(student.corrects) || 0;
              student.points = Number(student.points) || 0;
              student.attempts += 1;
            }
          }
        });
      } else if (typeof data == 'object') {
        const { stu_no, points, isRight } = data;
        const student = studentData.find(s => s.stu_no == stu_no);
        if (!student) return { success: false, message: '学生不存在' };
        if (isRight === 1) {
          student.attempts = Number(student.attempts) || 0;
          student.corrects = Number(student.corrects) || 0;
          student.points = Number(student.points) || 0;
          student.attempts += 1;
          student.corrects += 1;
          student.points += Number(points) || 0;
        } else {
          student.attempts = Number(student.attempts) || 0;
          student.corrects = Number(student.corrects) || 0;
          student.points = Number(student.points) || 0;
          student.attempts += 1;
        }
      } else {
        return { success: false, message: '无效的数据格式' };
      }
      await writeExcel(stufilePath, 'Students', studentData);
      return { success: true };
    } catch (error) {
      console.error('添加分数时出错:', error);
      return { success: false, error: error.message };
    }
  },

  async addAttempts(event, data) {
    try {
      if (!await fileExists(stufilePath)) return { success: false, message: '学生数据文件不存在' };
      let studentData = await readExcel(stufilePath, 'Students');
      if (Array.isArray(data)) {
        data.forEach(({ stu_no, attempts }) => {
          const student = studentData.find(s => s.stu_no == stu_no);
          if (student) {
            student.attempts = Number(student.attempts) || 0;
            student.corrects = Number(student.corrects) || 0;
            student.points = Number(student.points) || 0;
            student.attempts += Number(attempts) || 0;
          }
        });
      } else if (typeof data == 'object') {
        const { stu_no, attempts } = data;
        const student = studentData.find(s => s.stu_no == stu_no);
        if (!student) return { success: false, message: '学生不存在' };
        student.attempts = Number(student.attempts) || 0;
        student.corrects = Number(student.corrects) || 0;
        student.points = Number(student.points) || 0;
        student.attempts += Number(attempts) || 0;
      }
      await writeExcel(stufilePath, 'Students', studentData);
      return { success: true };
    } catch (error) {
      console.error('添加问答次数时出错:', error);
      return { success: false, error: error.message };
    }
  },
  async writeData(event, data) {
    try {
      await ensureDirectoryExistence(classfilePath);
      await ensureDirectoryExistence(stufilePath);
      const { classes, students } = data;
      await writeExcel(classfilePath, 'Classes', classes);
      await writeExcel(stufilePath, 'Students', students);

      return { success: true };
    } catch (error) {
      console.error('写入本地数据失败:', error);
      return { success: false, error: error.message };
    }
  }

};

module.exports = ipcHandlers;
